package com.yhn.weixin.utils;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.ByteArrayInputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class XmlUtil {

    /**
     * 将 xml 字符串 转换为 map
     <ResponseInfo>   --- xml 字符串
     <ResCode>Failed</ResCode>
     <ResMessage>Already in use</ResMessage>
     <ErrorNo>3</ErrorNo>
     </ResponseInfo>
     */
    public static Map<String, Object> parserXmlString(String[] keyParam,String xml) {
        // xml 字符串中可能包含的 key
        List<String> keys = new ArrayList<>();
        for (String s : keyParam) {
            keys.add(s);
        }
        Map<String, Object> map = new HashMap<>();

        SAXReader saxReader = new SAXReader();

        try {
            Document document = saxReader.read(
                    new ByteArrayInputStream( xml.getBytes() ) );
            Element responseInfo = document.getRootElement();

            for ( int i = 0; i < keys.size(); i++ ) {
                String key = keys.get( i );

                if ( responseInfo.elements( key ).isEmpty() == false ) {
                    Element Command = ( Element ) responseInfo.elements( key ).get( 0 );
                    Object value = Command.getData();

                    map.put( key, value );
                } else {
                    map.put( key, "" );
                }
            }
        } catch ( DocumentException e ) {
            System.out.println( e.getMessage() );
        }

        return map;
    }

}
